//
//  BaseRequestController.m
//  Kadima
//
//  Created by Fidetro on 2016/11/5.
//  Copyright © 2016年 Dtston. All rights reserved.
//

#import "BaseRequestController.h"
#import "GetUserInfoApi.h"
#import "KaiseruserDataGit.h"

@interface BaseRequestController ()

@end

@implementation BaseRequestController

- (void)startWithYTKRequest:(YTKRequest *)request
 completionBlockWithSuccess:(void (^)(YTKBaseRequest *request))success
                    failure:(void(^)(YTKBaseRequest *request))failure{
    
    [request startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        if ([[request responseJSONObject][@"errcode"]integerValue] == 0) {
            
            if ([[request responseJSONObject][@"errmsg"] respondsToSelector:@selector(length)] == YES) {
                
                [[request responseJSONObject][@"errmsg"]length] > 0 ? ([SVProgressHUD showSuccessWithStatus:[request responseJSONObject][@"errmsg"]]) : 0;
            }
            ;
            
            if (success) {
                success(request);
            }
         
        }else{
            
            if ([[request responseJSONObject][@"errmsg"] isEqualToString:@"没有数据"]) {
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[request responseJSONObject][@"errmsg"]];

            }
            
            
            
            if (failure) {
            failure(request);
            }
            
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        [SVProgressHUD showErrorWithStatus:@"网络无法连接"];
        
    }];
 
}

- (void)getUserInfo_block:(USERINFO_BLOCK)user_block{
    
    
    [[DTCloudManager defaultJNI_iOS_SDK] getUserInformationSuccessCallback:^(NSDictionary *dic) {
        
        UserInfo *userInfo = [UserInfo yy_modelWithJSON:dic[@"data"]];
        [KaiseruserDataGit saveUserInfo:userInfo];
        if (user_block) {
            
            user_block(userInfo);
            
        }

    } errorCallback:^(NSDictionary *dic) {
       
        if ([dic[@"errcode"] integerValue] == 400006) {
            
            [self signOutInfo];

            [[AppDelegate globalDelegate] setRootViewController];
            
            return [SVProgressHUD showErrorWithStatus:@"登录凭证实效，请重新登录"];
        }
        [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        
    }];
    
    
}



- (void)signOutInfo{
    
    [[DTCloudManager defaultJNI_iOS_SDK] logout];
    REMOVE_OBJECT(USERNAME);
    REMOVE_OBJECT(PASSWORD);
    REMOVE_OBJECT(DTUID);
    SAVE_BOOL(NO, LOGIN);

}

@end
